package com.suning.park.admin.epps.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.suning.park.admin.bean.Properties;
import com.suning.park.admin.exception.BusinessFailException;
import com.suning.park.admin.util.HttpUtil;
import com.suning.park.admin.util.JsonUtil;
import com.suning.park.admin.util.epps.PaymentHandler;
import com.suning.park.admin.epps.service.IEppsService;
import com.suning.park.dto.dao.ParkPayMapper;
import com.suning.park.dto.model.ParkPay;
import com.suning.park.dto.model.ParkPayExample;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

/**
 * 易付宝相关
 * Created by Administrator on 2017/1/12.
 */
@Service
public class EppsService implements IEppsService {
    private static final Logger logger = LoggerFactory.getLogger(EppsService.class);

    //易付宝响应成功标示
    private final static String SUCCESS = "0000";

    @Autowired
    PaymentHandler paymentHandler;
    @Autowired
    Properties properties;
    @Autowired
    ParkPayMapper parkPayMapper;

    /**
     * 易付宝支付参数构建
     *
     * @param parkId      车场ID
     * @param orderId     支付订单ID
     * @param goodsName   产品
     * @param orderAmount 订单金额
     * @param orderTime 订单时间
     * @return
     * @throws BusinessFailException
     */
    @Override
    public String pay(String parkId, String orderId, String goodsName, String orderAmount, String orderTime) throws BusinessFailException {
        if (Double.parseDouble(orderAmount) <= 0) {
            throw new BusinessFailException("支付金额不能小于0");
        }
        ParkPayExample example = new ParkPayExample();
        example.createCriteria().andParkIdEqualTo(parkId);
        List<ParkPay> list = parkPayMapper.selectByExample(example);
        if (list == null || list.size() < 1) {
            throw new BusinessFailException("未找到车场易付宝配置");
        }
        String salerMerchantNo = list.get(0).getMerchantNo();
        Map<String, String> data = Maps.newHashMap();
        data.put("merchantNo", salerMerchantNo);
        data.put("salerMerchantNo", salerMerchantNo);//卖家易付宝会员编号
        data.put("orderId", orderId);//支付订单ID
        data.put("goodsName", goodsName);//商品名称
        data.put("orderAmount", orderAmount);
        data.put("orderTime", orderTime);
        return paymentHandler.buildPayParams(data);
    }

    /**
     * 支付订单查询
     *
     * @param salerMerchantNo
     * @param orderId
     * @param orderTime
     * @return 订单状态：支付成功"S"，订单关闭"C"，新建"N"
     */
    public String selectOrder(String salerMerchantNo, String orderId, String orderTime) throws BusinessFailException{
        String params = paymentHandler.buildSelectOrderParams(salerMerchantNo, orderId, orderTime);
        String result = HttpUtil.doPost(properties.getEppsSelectOrderUrl(), params);
        Map map = JsonUtil.json2Map(result);
        if(SUCCESS.equals(MapUtils.getString(map, "responseCode"))){
            return MapUtils.getString(map, "orderStatus");
        }else{
            throw new BusinessFailException(MapUtils.getString(map, "responseMsg"));
        }
    }

    /**
     * 支付成功回调
     * @param orders  支付成功信息  json
     */
    @Transactional
    public void paySuccess(String orders) {
        JSONObject order = JSON.parseArray(orders).getJSONObject(0);
        String orderId = order.getString("outOrderNo");//商户唯一订单号
        String eppsOrderId = order.getString("orderId");//易付宝订单号
        String eppsCreateTime = order.getString("orderTime");//易付宝订单创建时间
        String paySuccessTime = order.getString("payTime");//支付完成时间
        String buyUserNo = order.getString("buyerUserNo");//买方用户号
        long orderAmount = order.getLong("orderAmount");//订单金额

    }

    /**
     * 退款
     * @param merchantNo 商户编号
     * @param refundOrderId 退订订单ID
     * @param refundOrderTime 退款时间
     * @param refundAmount 退款金额
     * @param orderId 支付订单ID
     * @param orderTime 订单时间
     * @return
     */
    public boolean refundOrder(String merchantNo, String refundOrderId, String refundOrderTime, String refundAmount, String orderId, String orderTime) {
        String params = paymentHandler.buildRefundOrderParams(merchantNo, refundOrderId, refundOrderTime, refundAmount, orderId, orderTime);
        String result = HttpUtil.doPost(properties.getEppsPayRefundUrl(), params);
        Map map = JsonUtil.json2Map(result);
        return MapUtils.getString(map,"responseCode").equals(SUCCESS);
    }


    /**
     * 退款通知
     * @param backOrderId 退款订单ID
     * @param backAmount 退款金额
     */
    public void refundNotify(String backOrderId,String backAmount){

    }

    /**
     * 退款订单查询
     * @param merchantNo 商户号
     * @param refundOrderNo 退款订单ID
     * @param refundOrderTime 退款订单时间
     * @return 00 退款处理中 01 退款成功 02：退款失败
     */
    public String queryRefundState(String merchantNo, String refundOrderNo, String refundOrderTime)throws BusinessFailException{
        String params = paymentHandler.buildSelectRefundOrderParams(merchantNo, refundOrderNo, refundOrderTime);
        String result = HttpUtil.doPost(properties.getEppsSelectOrderUrl(), params);
        Map map = JsonUtil.json2Map(result);
        if(SUCCESS.equals(MapUtils.getString(map, "responseCode"))){
            return MapUtils.getString(map, "status");
        }else{
            throw new BusinessFailException(MapUtils.getString(map, "responseMsg"));
        }
    }




    /**
     * 构建支付请求参数
     *
     * @param salerMerchantNo 每个车场一个易付宝商户号
     * @param orderId         订单ID
     * @param goodsName       商品名称
     * @param orderAmount     订单金额
     * @param orderTime       订单创建时间
     * @return
     */
    @Override
    public String testpayment(String salerMerchantNo, String orderId, String goodsName, String orderAmount, String orderTime) throws BusinessFailException {
        if (Double.parseDouble(orderAmount) <= 0) {
            throw new BusinessFailException("支付金额不能小于0");
        }
        Map<String, String> data = Maps.newHashMap();
        data.put("merchantNo", salerMerchantNo);
        data.put("salerMerchantNo", salerMerchantNo);//卖家易付宝会员编号
        data.put("orderId", orderId);//支付订单ID
        data.put("goodsName", goodsName);//商品名称
        data.put("orderAmount", orderAmount);
        data.put("orderTime", orderTime);
        return paymentHandler.buildPayParams(data);
    }


}
